package com.qiaofang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wenhao.jpa.Specifications;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.common.constant.ExceptionEnum;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.model.PageDTO;
import com.qiaofang.common.model.UiListBean;
import com.qiaofang.common.utils.DateUtil;
import com.qiaofang.common.utils.HttpUtil;
import com.qiaofang.common.utils.PageUtil;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.constant.*;
import com.qiaofang.dto.*;
import com.qiaofang.entity.*;
import com.qiaofang.mapper.ApiLogMapper;
import com.qiaofang.mapper.ReportMapper;
import com.qiaofang.repository.*;
import com.qiaofang.service.ReportService;
import com.qiaofang.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ApiLogMapper apiLogMapper;

    @Autowired
    private ApiLogRepository apiLogRepository;

    @Autowired
    private FollowUpRepository followUpRepository;

    @Autowired
    private OtherCompanyRepository otherCompanyRepository;

    @Autowired
    private ApiLogSendV10AgainRepository apiLogSendV10AgainRepository;

    @Autowired
    private CustomerPremisesRepository customerPremisesRepository;

    @Override
    public UiListBean<ReportVO> listReport(ListReportDTO dto, PageDTO page) {
        //处理参数
        ReportDTO reportDTO = new ReportDTO();
        if (dto != null) {
            if (StringUtil.isNotBlank(dto.getReportDeptName())) {
                reportDTO.setReportDeptName(StringUtil.addLikeParam(dto.getReportDeptName()));
            }
            if (StringUtil.isNotBlank(dto.getCreateTimeStart())) {
                reportDTO.setCreateTimeStart(DateUtil.minOfString(dto.getCreateTimeStart()));
            }
            if (StringUtil.isNotBlank(dto.getCreateTimeEnd())) {
                reportDTO.setCreateTimeEnd(DateUtil.maxOfString(dto.getCreateTimeEnd()));
            }
            if (StringUtil.isNotBlank(dto.getSearchContent())) {
                reportDTO.setSearchContent(StringUtil.addLikeParam(dto.getSearchContent()));
            }
        }
        if (page == null) {
            page = new PageDTO();
        }
        Long count = reportMapper.countListReport(reportDTO);
        List<ReportVO> vos = Lists.newArrayList();
        if (count > 0) {
            List<Report> list = reportMapper.listReport(reportDTO, page);
            if (list != null) {
                for (Report report : list) {
                    ReportVO vo = convertDomain2VO(report);
                    vos.add(vo);
                }
            }
        }
        UiListBean<ReportVO> uiListBean = new UiListBean<>();
        uiListBean.setList(vos);
        uiListBean.setTotalCount(count);
        return uiListBean;
    }

    private ReportVO convertDomain2VO(Report report) {
        if (report == null) {
            return null;
        }
        ReportVO vo = new ReportVO();
        vo.setId(report.getId());
        vo.setSource("V10报备");
        vo.setPremisesName(report.getPremisesName());
        vo.setCustomerName(report.getCustomerName());
        vo.setCustomerPhone(report.getCustomerPhone());
        vo.setReportName(report.getReportName());
        vo.setRecommenderName(report.getRecommenderName());
        if (StringUtil.isNotBlank(report.getReportPhone())) {
            vo.setReportPhone(report.getReportPhone());
        } else {
            vo.setReportPhone(report.getPartnerPhone());
        }
        vo.setReportDeptName(report.getReportDeptName());
        vo.setCreateTime(report.getCreateTime());
        vo.setLastUpdateTime(report.getLastUpdateTime());
        if (report.getConfirmStatus() == null && report.getCustomerStatus() == null) {
            vo.setConfirmStatus("");
            vo.setSyncStatus("");
        } else {
            if (StringUtil.equals(report.getConfirmStatus(), ConfirmStatusEnum.confirm.getNo())) {
                CustomerStatusEnum customerStatusEnum = CustomerStatusEnum.getByNo(report.getCustomerStatus());
                if (customerStatusEnum != null) {
                    vo.setConfirmStatus(customerStatusEnum.getDes());
                }
            } else {
                ConfirmStatusEnum confirmStatusEnum = ConfirmStatusEnum.getByNo(report.getConfirmStatus());
                if (confirmStatusEnum != null) {
                    vo.setConfirmStatus(confirmStatusEnum.getDes());
                }
            }
            if (report.getApiLogCount() == null) {
                vo.setSyncStatus("状态未知");
            } else if (report.getApiLogCount() > 0) {
                vo.setSyncStatus("同步异常");
            } else {
                vo.setSyncStatus("已同步");
            }
        }
        return vo;
    }

    @Override
    public ReportVO getReport(Long id) {
        Report report = reportMapper.getReport(id);
        ReportVO reportVO = convertDomain2VO(report);
        if (reportVO != null) {
            //交易状态变更记录列表
            //4001 代码中没有用到这个错误代码 报备审核直接用了4002
            //     customer status = 0  报备
            //4002 customer status = 10 审核
            //4003 customer status = 6  到访
            //4004 customer status = -1 无效报备
            //4005 confirm status = 1   认筹
            //4006 confirm status = 2   认购
            //4007 confirm status = 3   签约
            //4008 confirm status = 4   交易失败
            FollowUp exampleFollowUp = new FollowUp();
            exampleFollowUp.setCustomerPremisesId(id);
            List<FollowUp> followUps = followUpRepository.findAll(Example.of(exampleFollowUp), PageUtil.getCreateTimeAsc());
            if (followUps != null && followUps.size() > 0) {
                Map<String, TradingStatusLogVO> tradingStatusLogVOMap = Maps.newConcurrentMap();
                ApiLog example = new ApiLog();
                example.setOtherRelationId(String.valueOf(reportVO.getId()));
                List<ApiLog> apiLogs = apiLogRepository.findAll(Example.of(example), PageUtil.getCreateTimeAsc());
                for (FollowUp followUp : followUps) {
                    if (!tradingStatusLogVOMap.containsKey(followUp.getNewCustomerStatus())) {
                        TradingStatusLogVO vo = new TradingStatusLogVO();
                        CustomerStatusEnum customerStatusEnum = CustomerStatusEnum.getByNo(followUp.getNewCustomerStatus());
                        if (customerStatusEnum != null) {
                            if (customerStatusEnum.getApiAction() == null) {
                                //不需要同步
                                vo.setStatus(customerStatusEnum.getDes());
                                vo.setSyncResult(false);
                                vo.setRemark("不需要同步");
                            } else {
                                vo.setStatus(customerStatusEnum.getDes());
                                for (int i = apiLogs.size() - 1; i >= 0; i--) {
                                    ApiLog apiLog = apiLogs.get(i);
                                    if (customerStatusEnum.getApiAction() != null && customerStatusEnum.getApiAction().equals(apiLog.getBusinessType())) {
                                        if (StringUtil.equals("{\"responseCode\":\"1\",\"responseMessage\":\"success\"}", apiLog.getResponseContent())) {
                                            vo.setSyncResult(true);
                                        } else {
                                            vo.setSyncResult(false);
                                        }
                                        vo.setSyncTime(apiLog.getCreateTime());
                                        vo.setRemark(apiLog.getRemark());
                                        break;
                                    }
                                }
                                if (vo.getSyncResult() == null) {
                                    vo.setSyncResult(false);
                                    vo.setRemark("未找到对应的记录");
                                }
                            }
                        } else {
                            vo.setStatus(followUp.getNewCustomerStatus());
                        }
                        vo.setChangeTime(followUp.getCreateTime());
                        tradingStatusLogVOMap.put(followUp.getNewCustomerStatus(), vo);
                    } else if (!tradingStatusLogVOMap.containsKey(followUp.getNewConfirmStatus())) {
                        if (StringUtil.equals("0", followUp.getNewConfirmStatus())) {
                            continue;
                        }
                        TradingStatusLogVO vo = new TradingStatusLogVO();
                        ConfirmStatusEnum confirmStatusEnum = ConfirmStatusEnum.getByNo(followUp.getNewConfirmStatus());
                        if (confirmStatusEnum != null) {
                            if (confirmStatusEnum.getApiAction() == null) {
                                //不需要同步
                                vo.setStatus(confirmStatusEnum.getDes());
                                vo.setSyncResult(false);
                                vo.setRemark("不需要同步");
                            } else {
                                vo.setStatus(confirmStatusEnum.getDes());
                                for (int i = apiLogs.size() - 1; i >= 0; i--) {
                                    ApiLog apiLog = apiLogs.get(i);
                                    if (confirmStatusEnum.getApiAction() != null && confirmStatusEnum.getApiAction().equals(apiLog.getBusinessType())) {
                                        if (StringUtil.equals("{\"responseCode\":\"1\",\"responseMessage\":\"success\"}", apiLog.getResponseContent())) {
                                            vo.setSyncResult(true);
                                        } else {
                                            vo.setSyncResult(false);
                                        }
                                        vo.setSyncTime(apiLog.getCreateTime());
                                        vo.setRemark(apiLog.getRemark());
                                        break;
                                    }
                                }
                                if (vo.getSyncResult() == null) {
                                    vo.setSyncResult(false);
                                    vo.setRemark("未找到对应的记录");
                                }
                            }
                        } else {
                            vo.setStatus(followUp.getNewConfirmStatus());
                        }
                        vo.setChangeTime(followUp.getCreateTime());
                        tradingStatusLogVOMap.put(followUp.getNewConfirmStatus(), vo);
                    }
                }
                List<TradingStatusLogVO> tradingStatusLogVOS = Lists.newArrayList();
                for (Map.Entry<String, TradingStatusLogVO> stringTradingStatusLogVOEntry : tradingStatusLogVOMap.entrySet()) {
                    tradingStatusLogVOS.add(stringTradingStatusLogVOEntry.getValue());
                }
                Collections.sort(tradingStatusLogVOS);
                reportVO.setTradingStatusLog(tradingStatusLogVOS);
                if (apiLogs != null) {
                    List<ApiLogVO> apiLogVOS = Lists.newArrayList();
                    for (ApiLog apiLog : apiLogs) {
                        ApiLogVO vo = new ApiLogVO();
                        ApiActionEnum apiActionEnum = ApiActionEnum.getByNo(apiLog.getBusinessType());
                        if (apiActionEnum != null) {
                            vo.setStatus(apiActionEnum.getDes());
                        }
                        vo.setSyncTime(apiLog.getCreateTime());
                        if (StringUtil.equals("{\"responseCode\":\"1\",\"responseMessage\":\"success\"}", apiLog.getResponseContent())) {
                            vo.setSyncResult(true);
                        } else {
                            vo.setSyncResult(false);
                        }
                        vo.setRequestContent(apiLog.getRequestContent());
                        vo.setResponseContent(apiLog.getResponseContent());
                        vo.setRemark(apiLog.getRemark());
                        apiLogVOS.add(vo);
                    }
                    reportVO.setSyncLog(apiLogVOS);
                }
            }

        }
        return reportVO;
    }

    @Override
    public void sendStatus(Long id) {
        List<ApiLog> apiLogs = apiLogMapper.listApiLog(String.valueOf(id));
        if (apiLogs != null && apiLogs.size() > 0) {
            for (ApiLog apiLog : apiLogs) {
                ApiLog newApiLog = new ApiLog();
                try {
                    if (StringUtil.isNotBlank(apiLog.getUrl()) && StringUtil.isNotBlank(apiLog.getRequestContent())) {
                        newApiLog.setOtherCompanyId(apiLog.getOtherCompanyId());
                        newApiLog.setCompanyId(apiLog.getCompanyId());
                        newApiLog.setPremisesId(apiLog.getPremisesId());
                        newApiLog.setPremisesName(apiLog.getPremisesName());
                        newApiLog.setOtherRelationId(apiLog.getOtherRelationId());
                        newApiLog.setPartnerId(apiLog.getPartnerId());
                        newApiLog.setPartnerName(apiLog.getPartnerName());
                        newApiLog.setBusinessType(apiLog.getBusinessType());
                        if (apiLog.getRecordCount() != null) {
                            newApiLog.setRecordCount(apiLog.getRecordCount() + 1);
                        } else {
                            newApiLog.setRecordCount(1);
                        }
                        newApiLog.setCreateTime(new Date());
                        newApiLog.setRequestContent(apiLog.getRequestContent());
                        newApiLog.setContent(apiLog.getRequestContent());
                        newApiLog.setUrl(apiLog.getUrl());
                        OtherCompany otherCompany = new OtherCompany();
                        otherCompany.setCompanyUuid(apiLog.getOtherCompanyId());
                        otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                        List<OtherCompany> otherCompanyList = otherCompanyRepository.findAll(Example.of(otherCompany));
                        if (otherCompanyList == null || otherCompanyList.size() == 0) {
                            throw new RuntimeException("公司相关信息为空,未发送请求");
                        }
                        newApiLog.setRemark("请求V10: " + otherCompanyList.get(0).getCompanyUuid());
                        if (apiLog.getRecordCount() != null) {
                            newApiLog.setRecordCount(apiLog.getRecordCount() + 1);
                        } else {
                            newApiLog.setRecordCount(1);
                        }
                        String result = HttpUtil.doPostV10(apiLog.getUrl(), apiLog.getRequestContent(),
                                otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(),
                                otherCompanyList.get(0).getCompanyUuid());
                        newApiLog.setResponseContent(result);
                        BaseResponseDto brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                        if (StringUtil.equals(brDto.getResponseCode(), "1")) {
                            //成功
                        } else {
                            //失败
                            throw new BusinessException(brDto.getResponseMessage());
                        }
                    }
                } catch (Exception e) {
                    log.error("sendStatus error: {}", e);
                    newApiLog.setRequestContent(apiLog.getRequestContent());
                    newApiLog.setContent(e.getMessage());
                    newApiLog.setResponseContent(e.getMessage());
                    throw new BusinessException("同步状态失败!");
                } finally {
                    apiLogRepository.save(newApiLog);
                    ApiLogSendV10Again apiLogSendV10Again = new ApiLogSendV10Again();
                    apiLogSendV10Again.setApiId(apiLog.getId());
                    apiLogSendV10Again.setCreateTime(new Date());
                    apiLogSendV10AgainRepository.save(apiLogSendV10Again);
                }
            }
        } else {
            throw new BusinessException("找不到异常记录日志，无法手动同步!");
        }
    }

    @Override
    public UiListBean<CusPreHistoryVO> listCusPreHistory(ListCusPreHistoryDTO dto, PageDTO page) {
        Report report = new Report();
        report.setMobile(dto.getMobile());
        report.setDevCompany(dto.getDevCompany());
        report.setAgentCompany(dto.getAgentCompany());
        report.setPremisesName(dto.getPremisesName());
        report.setType(dto.getType());
        report.setCreateTimeStart(dto.getCreateTimeStart());
        report.setCreateTimeEnd(dto.getCreateTimeEnd());
        Long count = reportMapper.countListCusPreHistory(report);
        List<CusPreHistoryVO> vos = Lists.newArrayList();
        if (count > 0) {
            List<Report> list = reportMapper.listCusPreHistory(report, page);
            if (list != null) {
                for (Report returnReport : list) {
                    CusPreHistoryVO vo = new CusPreHistoryVO();
                    vo.setId(returnReport.getId());
                    vo.setDevCompany(returnReport.getDevCompany());
                    vo.setPremisesName(returnReport.getPremisesName());
                    vo.setStaffId(returnReport.getStaffId());
                    vo.setAccountName(returnReport.getAccountName());
                    vo.setAgentCompany(returnReport.getAgentCompany());
                    vo.setCustomerName(returnReport.getCustomerName());
                    vo.setMobile(returnReport.getMobile());
                    if ("normal".equals(returnReport.getType())) {
                        vo.setType("基础表");
                    } else if ("backend".equals(returnReport.getType())) {
                        vo.setType("备份表");
                    }
                    vo.setCreateTime(returnReport.getCreateTime());
                    vos.add(vo);
                }
            }
        }
        UiListBean<CusPreHistoryVO> uiListBean = new UiListBean<>();
        uiListBean.setList(vos);
        uiListBean.setTotalCount(count);
        return uiListBean;
    }

    @Override
    public UiListBean<CusPreNormalVO> listCusPreNormal(ListCusPreNormalDTO dto, PageDTO page) {
        Report report = new Report();
        report.setMobile(dto.getMobile());
        report.setDevCompany(dto.getDevCompany());
        report.setAgentCompany(dto.getAgentCompany());
        report.setPremisesName(dto.getPremisesName());
        report.setCustomerStatus(dto.getCustomerStatus());
        report.setConfirmStatus(dto.getConfirmStatus());
        report.setCreateTimeStart(dto.getCreateTimeStart());
        report.setCreateTimeEnd(dto.getCreateTimeEnd());
        Long count = reportMapper.countListCusPreNormal(report);
        List<CusPreNormalVO> vos = Lists.newArrayList();
        if (count > 0) {
            List<Report> list = reportMapper.listCusPreNormal(report, page);
            if (list != null) {
                for (Report returnReport : list) {
                    CusPreNormalVO vo = new CusPreNormalVO();
                    vo.setId(returnReport.getId());
                    vo.setDevCompany(returnReport.getDevCompany());
                    vo.setPremisesName(returnReport.getPremisesName());
                    vo.setStaffId(returnReport.getStaffId());
                    vo.setAccountName(returnReport.getAccountName());
                    vo.setAgentCompany(returnReport.getAgentCompany());
                    vo.setCustomerName(returnReport.getCustomerName());
                    vo.setMobile(returnReport.getMobile());
                    vo.setHopeVisitTime(returnReport.getHopeVisitTime());
                    vo.setCustomerStatus("");
                    vo.setConfirmStatus("");
                    vo.setRecommenderName(StringUtils.isEmpty(returnReport.getRecommenderName()) ? "无" : returnReport.getRecommenderName());
                    if (StringUtils.isNotBlank(returnReport.getCustomerStatus())) {
                        vo.setCustomerStatus(CustomerStatusEnum.getByNo(returnReport.getCustomerStatus()).getDes());
                    }
                    if (StringUtils.isNotBlank(returnReport.getConfirmStatus())) {
                        vo.setConfirmStatus(ConfirmStatusEnum.getByNo(returnReport.getConfirmStatus()).getDes());
                    }
                    vo.setCreateTime(returnReport.getCreateTime());
                    vos.add(vo);
                }
            }
        }
        UiListBean<CusPreNormalVO> uiListBean = new UiListBean<>();
        uiListBean.setList(vos);
        uiListBean.setTotalCount(count);
        return uiListBean;
    }

    @Override
    public UiListBean listFollow(ListFollowDTO dto) {
        FollowUp exampleFollowUp = new FollowUp();
        exampleFollowUp.setCustomerPremisesId(dto.getCustomerPremisesId());
        List<FollowUp> followList = followUpRepository.findAll(Example.of(exampleFollowUp), PageUtil.getCreateTimeAsc());
        UiListBean<FollowVO> uiListBean = new UiListBean();
        List<FollowVO> followVOS = Lists.newArrayList();
        if (null != followList && followList.size() > 0) {
            for (FollowUp follow : followList) {
                FollowVO followVO = new FollowVO();
                followVO.setId(follow.getId());
                followVO.setCustomerPremisesId(follow.getCustomerPremisesId());
                followVO.setOldCustomerStatus("");
                followVO.setNewCustomerStatus("");
                followVO.setOldConfirmStatus("");
                followVO.setNewConfirmStatus("");
                if (StringUtils.isNotBlank(follow.getOldCustomerStatus())) {
                    followVO.setOldCustomerStatus(CustomerStatusEnum.getByNo(follow.getOldCustomerStatus()).getDes());
                }
                if (StringUtils.isNotBlank(follow.getNewCustomerStatus())) {
                    followVO.setNewCustomerStatus(CustomerStatusEnum.getByNo(follow.getNewCustomerStatus()).getDes());
                }
                if (StringUtils.isNotBlank(follow.getOldConfirmStatus())) {
                    followVO.setOldConfirmStatus(ConfirmStatusEnum.getByNo(follow.getOldConfirmStatus()).getDes());
                }
                if (StringUtils.isNotBlank(follow.getNewConfirmStatus())) {
                    followVO.setNewConfirmStatus(ConfirmStatusEnum.getByNo(follow.getNewConfirmStatus()).getDes());
                }
                followVO.setCreateTime(follow.getCreateTime());
                followVO.setUpdateTime(follow.getUpdateTime());
                followVO.setRemark(follow.getRemark());
                followVOS.add(followVO);
            }
        }
        uiListBean.setList(followVOS);
        return uiListBean;
    }

    @Override
    public void changeCusPreStatus(ChangeCusPreStatusDTO dto) {
        CustomerPremises cusPre = customerPremisesRepository.findById(dto.getCustomerPremisesId())
                .orElseThrow(() -> new BusinessException(ExceptionEnum.NOT_FIND_DB_DATA));

        FollowUp followUp = new FollowUp();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 7);
        followUp.setCreateTime(calendar.getTime());
        followUp.setCustomerPremisesId(dto.getCustomerPremisesId());
        followUp.setStaffId(cusPre.getStaffId());
        followUp.setOldCustomerStatus(cusPre.getCustomerStatus());
        followUp.setNewCustomerStatus(dto.getCustomerStatus());
        followUp.setOldConfirmStatus(cusPre.getConfirmStatus());
        followUp.setNewConfirmStatus(cusPre.getConfirmStatus());
        followUp.setRemark("【状态强制变更】" + dto.getRemark());
        followUp.setFollowType(FollowTypeEnum.DEVELOPERS.getNo());
        followUpRepository.save(followUp);

        cusPre.setCustomerStatus(dto.getCustomerStatus());
        if(CustomerStatusEnum.not_visited.getNo().equals(dto.getCustomerStatus())){
            cusPre.setHopeVisitTime(calendar.getTime());
        }
        customerPremisesRepository.save(cusPre);
    }

    private void reportChangeInvalidstatus(List<CustomerPremises> list) {
        if(CollectionUtils.isNotEmpty(list)){
            log.info("reportChangeInvalidstatus empty is : {}", JSONObject.toJSONString(list));
            List<FollowUp> followUpList = org.apache.commons.compress.utils.Lists.newArrayList();
            for (CustomerPremises cp : list){
                Date newDate = DateUtils.addMinutes(cp.getReportValidTime(), 1);
                FollowUp followUp = new FollowUp();
                followUp.setCreateTime(newDate);
                followUp.setCustomerPremisesId(cp.getId());
                followUp.setNewConfirmStatus(ConfirmStatusEnum.confirm.getNo());
                followUp.setNewCustomerStatus(CustomerStatusEnum.normal.getNo());
                followUp.setStaffId(cp.getStaffId());
                followUp.setFollowType(FollowTypeEnum.CHANNEL.getNo());
                followUp.setRemark("【报备超时未到访】超过报备有效期，转为无效报备");
                followUp.setFollowUpType(FollowUpEnum.status_transfer.getNo());
                followUpList.add(followUp);
                cp.setUpdateTime(new Date());
                cp.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                customerPremisesRepository.save(cp);
            }
            log.info("reportChangeInvalidstatus followUpList empty is : {}", JSONObject.toJSONString(followUpList));
            if(CollectionUtils.isNotEmpty(followUpList)){
                followUpRepository.saveAll(followUpList);
            }
        }
    }

    private void reportVisitChangeInvalidstatus(List<CustomerPremises> list) {
        if(CollectionUtils.isNotEmpty(list)){
            log.info("reportVisitChangeInvalidstatus empty is : {}", JSONObject.toJSONString(list));
            List<FollowUp> followUpList = org.apache.commons.compress.utils.Lists.newArrayList();
            for (CustomerPremises cp : list){
                Date newDate = DateUtils.addMinutes(cp.getReportValidTime(), 1);
                FollowUp followUp = new FollowUp();
                followUp.setCreateTime(newDate);
                followUp.setCustomerPremisesId(cp.getId());
                followUp.setNewConfirmStatus(ConfirmStatusEnum.confirm.getNo());
                followUp.setNewCustomerStatus(CustomerStatusEnum.normal.getNo());
                followUp.setStaffId(cp.getStaffId());
                followUp.setFollowType(FollowTypeEnum.CHANNEL.getNo());
                followUp.setRemark("【报备超时未交易】客户超时未交易，转为无效客户");
                followUp.setFollowUpType(FollowUpEnum.status_transfer.getNo());
                followUpList.add(followUp);
                cp.setUpdateTime(new Date());
                cp.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                customerPremisesRepository.save(cp);
            }
            log.info("reportVisitChangeInvalidstatus followUpList empty is : {}", JSONObject.toJSONString(followUpList));
            if(CollectionUtils.isNotEmpty(followUpList)){
                followUpRepository.saveAll(followUpList);
            }
        }
    }

    @Override
    public void clearInvalidReportByPremisesId(Long premisesId) {
        if(premisesId == null){
            return;
        }
        Specification<CustomerPremises> specification = Specifications.<CustomerPremises>and()
                .eq("customerStatus", CustomerStatusEnum.not_visited.getNo())
                .eq("premisesId", premisesId)
                .lt("reportValidTime", new Date())
                .build();
        List<CustomerPremises> customerPremises = customerPremisesRepository.findAll(specification);
        log.info("clearInvalidReportByPremisesId List size is : {}", JSONObject.toJSONString(customerPremises));
        if(CollectionUtils.isNotEmpty(customerPremises)){
            List<List<CustomerPremises>> partitions = com.google.common.collect.Lists.partition(customerPremises, 500);
            for (List<CustomerPremises> list : partitions){
                reportChangeInvalidstatus(list);
            }
        }

        Specification<CustomerPremises> specification2 = Specifications.<CustomerPremises>and()
                .eq("customerStatus", CustomerStatusEnum.has_visited.getNo())
                .eq("premisesId", premisesId)
                .eq("confirmStatus", ConfirmStatusEnum.confirm.getNo())
                .lt("visitBaohuTime", new Date())
                .build();
        List<CustomerPremises> customerPremises2 = customerPremisesRepository.findAll(specification2);
        log.info("clearInvalidReportByPremisesId List size is : {}", JSONObject.toJSONString(customerPremises2));
        if(CollectionUtils.isNotEmpty(customerPremises2)){
            reportVisitChangeInvalidstatus(customerPremises2);
        }
    }

    @Override
    public int updateCustomerByCustomerIds(ReportDTO entity) {
        return reportMapper.updateCustomerByCustomerIds(entity);
    }

    @Override
    public void deleteCusPre(Long id) {
        CustomerPremises customerPremises=customerPremisesRepository.findById(id)
                .orElseThrow(()->new BusinessException(ExceptionEnum.NOT_FIND_DB_DATA));
        customerPremises.setDelFlag(DelFlagEnum.DEL.getNo());
        customerPremisesRepository.save(customerPremises);
    }
}
